package org.jeecg.modules.lab.utensil.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.cert.client.UserClient;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.device.service.ILabDeviceService;
import org.jeecg.modules.lab.documents.entity.LabDocuments;
import org.jeecg.modules.lab.documents.management_technology.lab_technology.entity.LabTechnology;
import org.jeecg.modules.lab.documents.service.ILabDocumentsService;
import org.jeecg.modules.lab.user.entity.SysUser;
import org.jeecg.modules.lab.utensil.entity.LabUtensil;
import org.jeecg.modules.lab.utensil.entity.LabUtensilTo;
import org.jeecg.modules.lab.utensil.service.ILabUtensilService;
import org.jeecg.modules.lab.utensil.vo.LabUtensilVo;
import org.jeecg.modules.lab.utensil.vo.UteResult;
import org.jeecg.modules.lab.util.FlowNumberUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 器具信息
 * @Author: jeecg-boot
 * @Date: 2023-07-11
 * @Version: V1.0
 */
@Api(tags = "器具信息")
@RestController
@RequestMapping("/utensil/labUtensil")
@Slf4j
public class LabUtensilController extends JeecgController<LabUtensil, ILabUtensilService> {
    @Resource
    private ILabUtensilService labUtensilService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ILabCronJobService labCronJobService;
    @Autowired
    private ILabDeviceService labDeviceService;

    @Autowired
    private ILabDocumentsService labDocumentsService;

    @Autowired
    private FlowNumberUtil flowNumberUtil;

    /**
     * 分页列表查询
     *
     * @param labUtensil
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "器具信息-分页列表查询")
    @ApiOperation(value = "器具信息-分页列表查询", notes = "器具信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabUtensilVo>> queryPageList(LabUtensil labUtensil,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<LabUtensil> queryWrapper = QueryGenerator.initQueryWrapper(labUtensil, req.getParameterMap());
        Page<LabUtensil> page = new Page<>(pageNo, pageSize);
        IPage<LabUtensil> pageList = labUtensilService.page(page, queryWrapper);
        //将器具的负责人转换为对应的名字
        Page<LabUtensilVo> labUtensilVoPage = getLabUtensilVoPage(pageNo, pageSize, pageList);
        return Result.OK(labUtensilVoPage);
    }

    /**
     * 将器具的负责人转换为对应的名字
     *
     * @param pageNo
     * @param pageSize
     * @param pageList
     * @return
     */
    private Page<LabUtensilVo> getLabUtensilVoPage(Integer pageNo, Integer pageSize, IPage<LabUtensil> pageList) {
        Page<LabUtensilVo> labUtensilVoPage = new Page<>(pageNo, pageSize);
        labUtensilVoPage.setTotal(pageList.getTotal());
        List<LabUtensilVo> utensilVos = new ArrayList<>();
        pageList.getRecords().forEach(e -> {
            LabUtensilVo labUtensilVo = new LabUtensilVo();
            BeanUtils.copyProperties(e, labUtensilVo);
            if (labUtensilVo.getPersonResponsible() != null && !labUtensilVo.getPersonResponsible().isEmpty()) {
                String[] split = labUtensilVo.getPersonResponsible().split(",");
                String perName = "";
                for (int i = 0; i < split.length; i++) {
                    SysUser user = userClient.queryById(split[i]).getResult();
                    if (i == split.length - 1) {
                        perName += user.getRealname();
                        break;
                    }
                    perName += user.getRealname() + ",";
                }
                labUtensilVo.setPersonResponsibleName(perName);
            }
            utensilVos.add(labUtensilVo);
        });
        labUtensilVoPage.setRecords(utensilVos);
        return labUtensilVoPage;
    }

    //待校验器具
    @GetMapping(value = "/listCheck")
    public Result<IPage<LabUtensilVo>> queryPageListCheck(LabUtensil labUtensil,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<LabUtensil> queryWrapper = QueryGenerator.initQueryWrapper(labUtensil, req.getParameterMap());
        queryWrapper.eq("status", "待检定");//这里添加条件，不能用getstatus，要用字符串获取
        Page<LabUtensil> page = new Page<LabUtensil>(pageNo, pageSize);
        IPage<LabUtensil> pageList = labUtensilService.page(page, queryWrapper);
        Page<LabUtensilVo> labUtensilVoPage = getLabUtensilVoPage(pageNo, pageSize, pageList);
        return Result.OK(labUtensilVoPage);
    }

    //校验中的器具
    @GetMapping(value = "/checking")
    public Result<IPage<LabUtensil>> checkingList(LabUtensil labUtensil,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<LabUtensil> queryWrapper = QueryGenerator.initQueryWrapper(labUtensil, req.getParameterMap());
        queryWrapper.eq("status", "检定中");//这里添加条件，不能用getstatus，要用字符串获取
        Page<LabUtensil> page = new Page<LabUtensil>(pageNo, pageSize);
        IPage<LabUtensil> pageList = labUtensilService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分类查询统计
     *
     * @return
     */
    @GetMapping(value = "/queryTypeList")
    public Result<List<LabUtensilTo>> queryType() {
        //按分类统计
        List<LabUtensilTo> labUtensilTos = labUtensilService.queryType();
        return Result.ok(labUtensilTos);
    }

    /**
     * 统计数量
     *
     * @return
     */
    @GetMapping(value = "/query")
    public Result<List<LabUtensilTo>> countAll() {

        return Result.ok(labUtensilService.countAll());
    }

    /**
     * 按状态查询统计
     *
     * @return
     */
    @GetMapping(value = "/queryStatusList")
    public Result<List<LabUtensilTo>> queryStatus() {
        //按状态统计
        List<LabUtensilTo> labUtensilTos = labUtensilService.queryStatus();
        return Result.ok(labUtensilTos);
    }

    /*
    /**
     *   添加
     *
     * @param labUtensil
     * @return
     */
    @AutoLog(value = "器具信息-添加")
    @ApiOperation(value = "器具信息-添加", notes = "器具信息-添加")
//	@RequiresPermissions("utensil:lab_utensil:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabUtensil labUtensil) {
        FlowNumberUtil flowNumberUtil = new FlowNumberUtil();
        //默认新增的器具状态是正常的
        labUtensil.setStatus("正常");
        //生成器具唯一编号
        labUtensil.setSerialNum(flowNumberUtil.utensilialNum());
        labUtensil.setSynFlag("0");
        labUtensilService.save(labUtensil);

        String instruct = labUtensil.getInstructions();
        if (!"".equals(instruct)) {
            LabDocuments labDocuments = new LabDocuments();
            labDocuments.setManagements("技术类");
            labDocuments.setDocType("计量");
            labDocuments.setDisplayName(labUtensil.getUteName());
            labDocuments.setCountdocId(labUtensil.getId());
            labDocuments.setUploadFiles(labUtensil.getInstructions());
            labDocuments.setSynFlag("0");
            labDocumentsService.save(labDocuments);
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_utensil", "0", time, 1));
            jobs.add(new LabCronJob("lab_documents", "0", time, 2));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labUtensil
     * @return
     */
    @AutoLog(value = "器具信息-编辑")
    @ApiOperation(value = "器具信息-编辑", notes = "器具信息-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabUtensil labUtensil) {
        long time = new Date().getTime();
        List<LabCronJob> jobs = new ArrayList<>();
        LabUtensil utensil = labUtensilService.getById(labUtensil.getId());
        if (utensil == null) {
            return Result.error("未找到对应的数据！");
        }
        labUtensil.setSynFlag("1");
        labUtensilService.updateById(labUtensil);
        jobs.add(new LabCronJob("lab_utensil", "1", time, 1));

        QueryWrapper<LabDocuments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("countdoc_id", labUtensil.getId());
        LabDocuments one = labDocumentsService.getOne(queryWrapper);
        String instruct = labUtensil.getInstructions();
        if (one == null && !"".equals(instruct)) {
            LabDocuments labDocuments = new LabDocuments();
            labDocuments.setManagements("技术类");
            labDocuments.setDocType("计量类");
            labDocuments.setSynFlag("0");
            labDocuments.setDisplayName(labUtensil.getUteName());
            labDocuments.setCountdocId(labUtensil.getId());
            labDocuments.setUploadFiles(labUtensil.getInstructions());
            labDocuments.setSynFlag("0");
            labDocumentsService.save(labDocuments);
            jobs.add(new LabCronJob("lab_documents", "0", time, 2));
        } else {
            one.setUploadFiles(labUtensil.getInstructions());
            one.setSynFlag("1");
            labDocumentsService.updateById(one);
            jobs.add(new LabCronJob("lab_documents", "1", time, 2));
        }

        if (MyEnum.sync) {
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("编辑成功!");
    }


    /**
     * 填写确认单
     *
     * @param labUtensil
     * @return
     */
    @RequestMapping(value = "/updateSure", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> updateSure(@RequestBody LabUtensil labUtensil) {
        try {
            labUtensilService.updateSure(labUtensil);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add(new LabCronJob("lab_utensil", "1", time, 1));
                jobs.add(new LabCronJob("lab_utensil_note", "0", time, 2));
                labCronJobService.saveBatch(jobs);
            }
            return Result.OK("填写完成!");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "器具信息-通过id删除")
    @ApiOperation(value = "器具信息-通过id删除", notes = "器具信息-通过id删除")
//	@RequiresPermissions("utensil:lab_utensil:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {

        long time = new Date().getTime();
        LabUtensil utensil = labUtensilService.getById(id);
        if (utensil.getDeviceId() != null && !utensil.getDeviceId().isEmpty()) {
            return Result.error("该器具属于设备，不能删除！");
        } else {
            labUtensilService.removeById(id);
            if (MyEnum.sync) {
                String conditionA = "id='" + id + "'";
                LabCronJob jobA = new LabCronJob("lab_utensil", "2", conditionA, time, 1);
                labCronJobService.save(jobA);
            }
            QueryWrapper<LabDocuments> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("countdoc_id", id);
            LabDocuments one = labDocumentsService.getOne(queryWrapper);
            if (one != null) {
                labDocumentsService.removeById(one);
                if (MyEnum.sync) {
                    String conditionB = "id='" + one.getId() + "'";
                    LabCronJob jobB = new LabCronJob("lab_documents", "2", conditionB, time, 2);
                    labCronJobService.save(jobB);
                }
            }
            return Result.OK("删除成功!");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "器具信息-批量删除")
    @ApiOperation(value = "器具信息-批量删除", notes = "器具信息-批量删除")
//	@RequiresPermissions("utensil:lab_utensil:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));

        for (String id : idList) {
            LabUtensil utensil = labUtensilService.getById(id);
            if (utensil.getDeviceId() != null && !utensil.getDeviceId().isEmpty()) {
                return Result.error("选中器具中有设备，删除失败！");
            }
        }
        labUtensilService.removeByIds(Arrays.asList(ids.split(",")));
        List<String> listId = new ArrayList<>();
        QueryWrapper<LabDocuments> queryWrapper = new QueryWrapper<>();
        for (String id : idList) {
            queryWrapper.clear();
            queryWrapper.eq("countdoc_id", id);
            LabDocuments one = labDocumentsService.getOne(queryWrapper);
            if (one != null) {
                listId.add(one.getId());
                labDocumentsService.removeById(one);
            }
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idArray = ids.split(",");
            labCronJobService.saveCronBatch("lab_utensil", "2", time, idArray);
            String[] dIds = listId.toArray(new String[0]);
            labCronJobService.saveCronBatch("lab_documents", "2", time, dIds);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "器具信息-通过id查询")
    @ApiOperation(value = "器具信息-通过id查询", notes = "器具信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<UteResult> queryById(@RequestParam(name = "id", required = true) String id) {
        LabUtensil labUtensil = labUtensilService.getById(id);
        UteResult uteResult = new UteResult();
        if (labUtensil != null) {
            if ("闲置".equals(labUtensil.getUseStatus())) {
                if ("正常".equals(labUtensil.getStatus())) {
                    uteResult.setCode("0");
                    uteResult.setUtensil(labUtensil);
                    return Result.ok(uteResult);
                } else {
                    uteResult.setCode("1");
                    uteResult.setMessage("该器具检定中！");
                    return Result.ok(uteResult);
                }
            } else if ("使用中".equals(labUtensil.getUseStatus())) {
                uteResult.setCode("1");
                uteResult.setMessage("该器具正在使用中！");
                return Result.ok(uteResult);
            } else {
                uteResult.setCode("0");
                uteResult.setUtensil(labUtensil);
                return Result.ok(uteResult);
            }
        } else {
            return Result.error("未找到对应数据");
        }
    }

    /**
     * 通过序号查询器具
     *
     * @param serialNum
     * @return
     */
    @ApiOperation(value = "器具信息-通过SerialNum查询", notes = "器具信息-通过SerialNum查询")
    @GetMapping(value = "/queryBySerialNum")
    public Result<UteResult> queryBySerialNum(@RequestParam(name = "serialNum", required = true) String serialNum) {
        QueryWrapper<LabUtensil> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("serial_Num", serialNum);
        LabUtensil labUtensil = labUtensilService.getOne(queryWrapper);
        UteResult uteResult = new UteResult();
        if (labUtensil != null) {
            if ("闲置".equals(labUtensil.getUseStatus())) {
                if ("正常".equals(labUtensil.getStatus())) {
                    uteResult.setCode("0");
                    uteResult.setUtensil(labUtensil);
                    return Result.ok(uteResult);
                } else {
                    uteResult.setCode("1");
                    uteResult.setMessage("该器具检定中！");
                    return Result.ok(uteResult);
                }
            } else if ("使用中".equals(labUtensil.getUseStatus())) {
                uteResult.setCode("1");
                uteResult.setMessage("该器具正在使用中！");
                return Result.ok(uteResult);
            } else {
                uteResult.setCode("0");
                uteResult.setUtensil(labUtensil);
                return Result.ok(uteResult);
            }
        } else {
            return Result.error("未找到对应数据");
        }
    }


    /**
     * 初始化器具唯一编码
     *
     * @return
     */
    @ApiOperation(value = "器具信息-初始化器具唯一编码", notes = "器具信息-初始化器具唯一编码")
    @GetMapping(value = "/initialSerialNum")
    public Result<String> initialSerialNum() {
        QueryWrapper<LabUtensil> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("serial_num");
        List<LabUtensil> labUtensilList = labUtensilService.list(queryWrapper);

        if (labUtensilList != null && labUtensilList.size() > 0) {
            for (LabUtensil labUtensil : labUtensilList) {
                String serialNum = labUtensil.getSerialNum();
                if (serialNum == null || "".equals(serialNum)) {
                    labUtensil.setSerialNum(flowNumberUtil.utensilialNum());
                }
            }
            labUtensilService.updateBatchById(labUtensilList);
            return Result.ok("器具唯一编码初始化完成！");
        } else {
            return Result.error("未找到对应数据！");
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labUtensil
     */
//    @RequiresPermissions("utensil:lab_utensil:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabUtensil labUtensil) {
        // 导出的字段
//		String datas= request.getParameter("myData");
//		if (datas!=null){
//			List<String> exportFields = Arrays.asList(datas.split(","));
//			return super.exportXls(request, labUtensil, LabUtensil.class, "器具信息",exportFields);
//		}else {
//
//		}
        return super.exportXls(request, labUtensil, LabUtensil.class, "器具信息");
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//    @RequiresPermissions("utensil:lab_utensil:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabUtensil.class);
    }

}
